/**
 * 剑指 Offer 25. 合并两个排序的链表
 * https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
 */
const { ListNode, displayListNode, createListNode } = require('../../libs/public');

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
function mergeTwoLists(l1, l2) {
  const head = new ListNode();
  let node = head;
  let node1 = l1;
  let node2 = l2;
  while (node1 && node2) {
    if (node1.val <= node2.val) {
      node.next = node1;
      node1 = node1.next;
    } else {
      node.next = node2;
      node2 = node2.next;
    }
    node = node.next;
  }
  node.next = node1 || node2;
  return head.next;
}

console.log(displayListNode(mergeTwoLists(createListNode([1, 2, 4]), createListNode([1, 3, 4]))) === '[1,1,2,3,4,4]');
console.log(displayListNode(mergeTwoLists(createListNode([1, 2, 4]), createListNode([]))) === '[1,2,4]');
console.log(displayListNode(mergeTwoLists(createListNode([]), createListNode([]))) === '[]');
